import { Column } from "@ant-design/charts"
import { MonthlySale, ProductQuery, ProductReport, ProductSale, SalesQuery, SalesReport } from "@mallfoundry/report"
import { Avatar, Button, Card, Col, DatePicker, Form, List, Row, Space, Statistic, Tabs, Typography } from "antd"
import * as dayjs from "dayjs"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import classes from "./sales-analysis.module.scss"

const { Title, Text } = Typography
const { RangePicker } = DatePicker
const { TabPane } = Tabs

const AMOUNT_FIELD_NAME = "销售额"

interface SalesColumnProps {
  storeId: string
}

function SalesColumn(props: SalesColumnProps) {
  const { storeId } = props
  const [data, setData] = useState([] as MonthlySale[])
  const asyncFetch = () => {
    SalesReport
      .queryMonthlySales(new SalesQuery().toBuilder().storeId(storeId)
        .dateFrom("20200101").dateTo("20201230").build())
      .then(sales => _.map(sales, sale => _.assign(new MonthlySale(), sale, {
        month: `${sale.month}月份`,
        [AMOUNT_FIELD_NAME]: sale.amount,
      })))
      .then(setData)
  }
  useEffect(asyncFetch, [storeId])
  const config = {
    height: 340,
    forceFit: true,
    smooth: true,
    data,
    xField: "month",
    yField: AMOUNT_FIELD_NAME,
    xAxis: {
      title: null,
      line: null,
      tickLine: null,
    },
    yAxis: {
      title: null,
      grid: {
        line: {
          style: {
            stroke: "black",
            lineWidth: 1,
            lineDash: [4, 2],
            strokeOpacity: 0.1,
          },
        },
      },
    },
  }
  return <Column {...config} />
}

interface ProductListProps {
  storeId: string
}

function ProductList(props: ProductListProps) {
  const { storeId } = props
  const [data, setData] = useState([] as ProductSale[])
  const asyncFetch = () => {
    ProductReport
      .queryProductSales(new ProductQuery().toBuilder().storeId(storeId)
        .dateFrom("20200101").dateTo("20201230").build())
      .then(pageProducts => pageProducts.elements)
      .then(setData)
  }
  useEffect(asyncFetch, [storeId])
  return <List className={classes.ProductList}
               itemLayout="horizontal"
               dataSource={data}
               renderItem={item => (
                 <List.Item>
                   <List.Item.Meta
                     avatar={<Avatar shape="square" size={28} src={item.imageUrl}/>}
                     description={
                       <Row className={classes.ProductListItem}
                            gutter={[16, 0]}
                            align="middle" justify="space-between">
                         <Col span={18}>
                           <Text ellipsis>{item.name}</Text>
                         </Col>
                         <Col span={6}>
                           <Statistic value={item.totalAmount}/>
                         </Col>
                       </Row>}/>
                 </List.Item>
               )}/>
}

interface SalesAnalysisProps {
  storeId: string
}

export default function SalesAnalysis(props: SalesAnalysisProps) {
  const { storeId } = props
  const actions = <>
    <Form
      initialValues={{ date: [dayjs(), dayjs()] }}>
      <Space size="large">
        <Button size="small">今日</Button>
        <Button size="small">本月</Button>
        <Button size="small">全年</Button>
        <Form.Item name="date" noStyle>
          <RangePicker/>
        </Form.Item>
      </Space>
    </Form>
  </>

  return (
    <Card className={classes.SalesAnalysis} size="small">
      <Tabs tabBarExtraContent={actions}>
        <TabPane tab="销售额" key="sales">
          <Row gutter={[24, 0]}>
            <Col span={17}>
              <SalesColumn storeId={storeId}/>
            </Col>
            <Col span={7}>
              <Title level={5}>商品销售额排名</Title>
              <ProductList storeId={storeId}/>
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="访问量" key="views">
          <Row gutter={[24, 0]}>
            <Col span={17}>
              <SalesColumn storeId={storeId}/>
            </Col>
            <Col span={7}>
              <Title level={5}>商品销售额排名</Title>
              <ProductList storeId={storeId}/>
            </Col>
          </Row>
        </TabPane>
      </Tabs>
    </Card>
  )
}
